package com.smart.community.property.controller;

import com.smart.community.commons.vo.property.PropertyInfoVO;
import com.smart.community.commons.vo.property.PropertyInfoListVO;
import com.smart.community.property.service.IUserPropertyCompanyService;
import com.smart.community.property.service.IPropertyCompanyService;
import com.smart.community.commons.entity.property.UserPropertyCompany;
import com.smart.community.property.vo.PropertyCompanyVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import javax.validation.constraints.NotNull;

import java.util.ArrayList;
import java.util.Collections;

/**
 * 用户物业公司关联Feign接口实现Controller
 * 
 * @author Wu.Liang
 * @version 1.0.0
 * @since 2025-06-29
 */
@Slf4j
@RestController
@RequestMapping("/property")
@Tag(name = "用户物业公司关联Feign接口", description = "用户物业公司关联相关Feign接口")
public class UserPropertyCompanyFeignController {

    @Autowired
    private IUserPropertyCompanyService userPropertyCompanyService;

    @Autowired
    private IPropertyCompanyService propertyCompanyService;

    /**
     * 根据用户ID查询物业信息（单个物业公司，兼容旧版本）
     * 
     * @param userId 用户ID
     * @return 物业信息
     */
    @GetMapping("/feign/user-companies/user/{userId}")
    @Operation(summary = "根据用户ID查询物业信息（单个物业公司，兼容旧版本）")
    public PropertyInfoVO getPropertyInfoByUserId(@Parameter(description = "用户ID") @PathVariable("userId") Long userId) throws Exception {
        log.info("根据用户ID查询物业信息（单个物业公司），用户ID：{}", userId);
        // 1. 获取用户关联的物业公司列表
        List<UserPropertyCompany> userPropertyCompanies = userPropertyCompanyService.getUserPropertyCompanies(userId);
        if (userPropertyCompanies == null || userPropertyCompanies.isEmpty()) {
            log.warn("用户{}未关联任何物业公司", userId);
            return new PropertyInfoVO();
        }

        // 2. 获取第一个关联的物业公司ID
        Long propertyCompanyId = userPropertyCompanies.get(0).getPropertyCompanyId();
        if (propertyCompanyId == null) {
            log.warn("用户{}关联的物业公司ID为空", userId);
            return new PropertyInfoVO();
        }

        // 3. 获取物业公司详细信息
        com.smart.community.commons.result.Result<PropertyCompanyVO> propertyCompanyResult = propertyCompanyService.getPropertyCompany(propertyCompanyId);
        if (!propertyCompanyResult.isSuccess() || propertyCompanyResult.getData() == null) {
            log.warn("获取物业公司信息失败，物业公司ID：{}", propertyCompanyId);
            return new PropertyInfoVO();
        }

        PropertyCompanyVO propertyCompanyVO = propertyCompanyResult.getData();

        // 4. 构建PropertyInfoVO对象
        PropertyInfoVO propertyInfoVO = buildPropertyInfoVO(propertyCompanyVO);

        log.info("成功获取用户{}的物业信息，物业公司：{}", userId, propertyCompanyVO.getCompanyName());
        return propertyInfoVO;
    }

    /**
     * 根据用户ID查询物业信息列表
     * 
     * @param userId 用户ID
     * @return 物业信息列表
     */
    @GetMapping("/feign/user-companies/user/{userId}/list")
    @Operation(summary = "根据用户ID查询物业信息列表")
    public PropertyInfoListVO getPropertyInfoListByUserId(@Parameter(description = "用户ID") @PathVariable("userId") Long userId) throws Exception {
        PropertyInfoListVO result = new PropertyInfoListVO();
        result.setUserId(userId);
        
        // 1. 获取用户关联的物业公司列表
        List<UserPropertyCompany> userPropertyCompanies = userPropertyCompanyService.getUserPropertyCompanies(userId);
        if (userPropertyCompanies == null || userPropertyCompanies.isEmpty()) {
            result.setPropertyCompanies(Collections.emptyList());
            result.setCount(0);
            result.setHasPropertyCompany(false);
            result.setDefaultPropertyCompany(null);
            return result;
        }

        // 2. 构建物业公司信息列表
        List<PropertyInfoVO> propertyInfoList = new ArrayList<>();
        PropertyInfoVO defaultPropertyCompany = null;
        
        for (UserPropertyCompany userPropertyCompany : userPropertyCompanies) {
            Long propertyCompanyId = userPropertyCompany.getPropertyCompanyId();
            if (propertyCompanyId == null) {
                continue;
            }

            // 3. 获取物业公司详细信息
            com.smart.community.commons.result.Result<PropertyCompanyVO> propertyCompanyResult = propertyCompanyService.getPropertyCompany(propertyCompanyId);
            if (!propertyCompanyResult.isSuccess() || propertyCompanyResult.getData() == null) {
                continue;
            }

            PropertyCompanyVO propertyCompanyVO = propertyCompanyResult.getData();
            PropertyInfoVO propertyInfoVO = buildPropertyInfoVO(propertyCompanyVO);
            propertyInfoList.add(propertyInfoVO);
            
            // 设置默认物业公司（第一个）
            if (defaultPropertyCompany == null) {
                defaultPropertyCompany = propertyInfoVO;
            }
        }

        // 4. 设置结果
        result.setPropertyCompanies(propertyInfoList);
        result.setCount(propertyInfoList.size());
        result.setHasPropertyCompany(!propertyInfoList.isEmpty());
        result.setDefaultPropertyCompany(defaultPropertyCompany);

        return result;
    }

    /**
     * 构建PropertyInfoVO对象
     * 
     * @param propertyCompanyVO 物业公司VO
     * @return PropertyInfoVO
     */
    private PropertyInfoVO buildPropertyInfoVO(PropertyCompanyVO propertyCompanyVO) {
        PropertyInfoVO propertyInfoVO = new PropertyInfoVO();
        propertyInfoVO.setPropertyCompanyId(propertyCompanyVO.getId());
        propertyInfoVO.setCompanyName(propertyCompanyVO.getCompanyName());
        propertyInfoVO.setCompanyCode(propertyCompanyVO.getCompanyCode());
        propertyInfoVO.setCreditCode(propertyCompanyVO.getCreditCode());
        propertyInfoVO.setLegalRepresentative(propertyCompanyVO.getLegalRepresentative());
        propertyInfoVO.setContactPhone(propertyCompanyVO.getContactPhone());
        propertyInfoVO.setContactEmail(propertyCompanyVO.getContactEmail());
        propertyInfoVO.setEmail(propertyCompanyVO.getEmail());
        propertyInfoVO.setAddress(propertyCompanyVO.getAddress());
        propertyInfoVO.setDescription(propertyCompanyVO.getIntroduction());
        propertyInfoVO.setBusinessLicense(propertyCompanyVO.getBusinessLicense());
        // 注意：PropertyInfoVO中是LocalDate，PropertyCompanyVO中是LocalDate，直接转换
        propertyInfoVO.setEstablishedDate(propertyCompanyVO.getEstablishedDate());
        // 注意：PropertyInfoVO中是BigDecimal，PropertyCompanyVO中是BigDecimal，直接转换
        propertyInfoVO.setRegisteredCapital(propertyCompanyVO.getRegisteredCapital());
        propertyInfoVO.setServiceScope(propertyCompanyVO.getServiceScope());
        propertyInfoVO.setStatus(propertyCompanyVO.getStatus());
        propertyInfoVO.setRemark(propertyCompanyVO.getRemark());
        propertyInfoVO.setCreateTime(propertyCompanyVO.getCreateTime());
        propertyInfoVO.setUpdateTime(propertyCompanyVO.getUpdateTime());
        
        return propertyInfoVO;
    }

    /**
     * 根据物业公司ID查询用户列表
     * 
     * @param propertyCompanyId 物业公司ID
     * @return 用户列表
     */
    @GetMapping("/feign/user-companies/property-company/{propertyCompanyId}")
    @Operation(summary = "根据物业公司ID查询用户列表")
    public PropertyInfoVO getUsersByPropertyCompanyId(@Parameter(description = "物业公司ID") @PathVariable("propertyCompanyId") Long propertyCompanyId) throws Exception {
        log.info("根据物业公司ID查询用户列表，物业公司ID：{}", propertyCompanyId);
        // 这里需要实现根据物业公司ID查询用户列表的逻辑
        // 暂时返回空结果，后续可以根据需要实现
        log.warn("getUsersByPropertyCompanyId方法暂未实现，物业公司ID：{}", propertyCompanyId);
        return new PropertyInfoVO();
    }

    /**
     * 检查用户是否有关联的物业公司
     * 
     * @param userId 用户ID
     * @return 是否有关联
     */
    @GetMapping("/feign/user-companies/check/{userId}")
    @Operation(summary = "检查用户是否有关联的物业公司")
    public Boolean checkUserHasPropertyCompany(@Parameter(description = "用户ID") @PathVariable("userId") Long userId) throws Exception {
        log.info("检查用户是否有关联的物业公司，用户ID：{}", userId);
        List<com.smart.community.commons.entity.property.UserPropertyCompany> userPropertyCompanies = 
                userPropertyCompanyService.getUserPropertyCompanies(userId);
        boolean hasPropertyCompany = userPropertyCompanies != null && !userPropertyCompanies.isEmpty();
        
        log.info("用户{}是否有关联的物业公司：{}，关联数量：{}", userId, hasPropertyCompany, 
                userPropertyCompanies != null ? userPropertyCompanies.size() : 0);
        
        return hasPropertyCompany;
    }
	
	@Operation(summary = "查询物业公司关联的用户ID", description = "查询物业公司关联的用户ID")
    @GetMapping("/feign/user-companies/user-list/{propertyCompanyId}")
	public List<Long> getUserIdsByPropertyCompanyId(@Parameter(description = "物业公司ID") @PathVariable @NotNull Long propertyCompanyId) throws Exception {
		 return userPropertyCompanyService.getUserIdsByPropertyCompanyId(propertyCompanyId);
	}
} 